<template>
    <div class="detail-page">
        <el-page-header content="销售订单详情" @back="handleClose" class="detail-header" />

        <el-card class="detail-card info-card" shadow="never">
            <div class="header-section">
                <div class="title-area">
                    <span class="order-label">销售单号：</span>
                    <span class="order-number">{{ info.salesOrderNo || '--' }}</span>
                    <el-tag :type="getStatusTagType(info.salesOrderStatus)" size="default" class="status-tag">
                        {{ getStatusText(info.salesOrderStatus) }}
                    </el-tag>
                </div>
                <div class="action-buttons">
                    <el-button type="primary" size="small" @click="handleEdit">编辑</el-button>
                    <el-button size="small" @click="handleCopyOrder">复制</el-button>
                    <el-button size="small" @click="handlePrint">打印</el-button>
                    <el-button type="danger" size="small" @click="handleDelete">删除</el-button>
                </div>
            </div>

            <div class="info-content">
                <el-descriptions :column="4" border>
                    <el-descriptions-item label="制单人">
                        {{ info.salesOrderUser || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="销售日期">
                        {{ formatDate(info.salesOrderDate) || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="联系方式">
                        {{ info.salesContactPhone || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="备注">
                        {{ info.remark || '-' }}
                    </el-descriptions-item>
                </el-descriptions>

                <el-descriptions :column="4" border class="info-row">
                    <el-descriptions-item label="所在部门">
                        {{ info.organizationName || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="客户名称">
                        {{ info.customerName || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="销售部门">
                        {{ info.organizationName || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="联系人">
                        {{ info.salesContact || '-' }}
                    </el-descriptions-item>
                </el-descriptions>

                <el-descriptions :column="4" border class="info-row">
                    <el-descriptions-item label="制单时间">
                        {{ formatDateTime(info.salesOrderTime) || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="销售负责人">
                        {{ info.userName || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="总数量">
                        {{ summary.totalQuantity }}
                    </el-descriptions-item>
                    <el-descriptions-item label="总金额">
                        ¥{{ summary.totalAmount.toFixed(2) }}
                    </el-descriptions-item>
                </el-descriptions>
            </div>
        </el-card>

        <el-card class="detail-card tabs-card" shadow="never">
            <div class="tabs-section">
                <el-tabs v-model="activeTab" type="card" class="detail-tabs" @tab-change="handleTabChange">
                    <el-tab-pane label="其他信息" name="other">
                        <div class="tab-content">
                            <el-descriptions :column="2" border class="other-info-descriptions">
                                <el-descriptions-item label="客户名称">
                                    {{ info.customerName || '-' }}
                                </el-descriptions-item>
                                <el-descriptions-item label="联系人">
                                    {{ info.salesContact || '-' }}
                                </el-descriptions-item>
                                <el-descriptions-item label="联系电话">
                                    {{ info.salesContactPhone || '-' }}
                                </el-descriptions-item>
                                <el-descriptions-item label="销售部门">
                                    {{ info.organizationName || '-' }}
                                </el-descriptions-item>
                                <el-descriptions-item label="制单备注" :span="2">
                                    {{ info.remark || '-' }}
                                </el-descriptions-item>
                            </el-descriptions>

                            <div class="section-block">
                                <div class="section-title">附件</div>
                                <div class="attachment-list" v-if="fileList.length">
                                    <el-link
                                        v-for="(file, index) in fileList"
                                        :key="index"
                                        type="primary"
                                        :href="file.url"
                                        target="_blank"
                                        class="file-link"
                                    >
                                        {{ file.name }}
                                    </el-link>
                                </div>
                                <div v-else class="empty-attachment">
                                    <el-icon class="attachment-icon">
                                        <Box />
                                    </el-icon>
                                    <span>暂无附件</span>
                                </div>
                            </div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="销售明细" name="details">
                        <div class="tab-content">
                            <el-table :data="detailList" border stripe style="width: 100%">
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="productName" label="货品名称" min-width="160" show-overflow-tooltip />
                                <el-table-column prop="productCode" label="货品编号" min-width="140" show-overflow-tooltip />
                                <el-table-column prop="specificationModel" label="规格型号" min-width="140" show-overflow-tooltip />
                                <el-table-column prop="unitName" label="单位" width="100" show-overflow-tooltip />
                                <el-table-column prop="productTypeName" label="货品类型" min-width="120" show-overflow-tooltip />
                                <el-table-column label="销售数量" width="120" align="right">
                                    <template #default="{ row }">
                                        {{ row.quantity ?? 0 }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="销售单价" width="130" align="right">
                                    <template #default="{ row }">
                                        ¥{{ Number(row.unitPrice ?? 0).toFixed(4) }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="金额" width="130" align="right">
                                    <template #default="{ row }">
                                        <span class="amount-text">¥{{ Number(row.amount ?? 0).toFixed(2) }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="remark" label="备注" min-width="160" show-overflow-tooltip />
                            </el-table>
                            <div class="detail-summary" v-if="detailList.length">
                                <span>货品种类：{{ detailList.length }}</span>
                                <span>销售总数量：{{ summary.totalQuantity }}</span>
                                <span>销售总金额：<span class="amount-text">¥{{ summary.totalAmount.toFixed(2) }}</span></span>
                            </div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="出库记录" name="outbound">
                        <div class="tab-content">
                            <el-table
                                :data="outboundRecords"
                                border
                                stripe
                                style="width: 100%"
                                v-loading="outboundLoading"
                            >
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="warehouseName" label="仓库" min-width="120" show-overflow-tooltip />
                                <el-table-column prop="productName" label="货品名称" min-width="160" show-overflow-tooltip />
                                <el-table-column prop="quantity" label="出库数量" width="120" align="right" />
                                <el-table-column label="出库时间" width="160">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.outboundTime) || '-' }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="operator" label="操作人" width="100" show-overflow-tooltip />
                                <el-table-column prop="remark" label="备注" min-width="180" show-overflow-tooltip />
                            </el-table>
                            <div v-if="!outboundRecords.length && !outboundLoading" class="empty-text">暂无出库记录</div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="退货记录" name="return">
                        <div class="tab-content">
                            <el-table
                                :data="returnRecords"
                                border
                                stripe
                                style="width: 100%"
                                v-loading="returnLoading"
                            >
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="productName" label="货品名称" min-width="160" show-overflow-tooltip />
                                <el-table-column prop="quantity" label="退货数量" width="120" align="right" />
                                <el-table-column label="退货时间" width="160">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.returnTime) || '-' }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="reason" label="退货原因" min-width="200" show-overflow-tooltip />
                                <el-table-column prop="operator" label="操作人" width="100" show-overflow-tooltip />
                            </el-table>
                            <div v-if="!returnRecords.length && !returnLoading" class="empty-text">暂无退货记录</div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="操作记录" name="logs">
                        <div class="tab-content">
                            <el-table
                                :data="operationRecords"
                                border
                                stripe
                                style="width: 100%"
                                v-loading="operationLoading"
                            >
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="operationType" label="操作类型" min-width="120" />
                                <el-table-column label="操作时间" width="160">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.operationTime) || '-' }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="operator" label="操作人" width="100" show-overflow-tooltip />
                                <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
                            </el-table>
                            <div v-if="!operationRecords.length && !operationLoading" class="empty-text">暂无操作记录</div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="审核记录" name="approval">
                        <div class="tab-content">
                            <el-table
                                :data="approvalRecords"
                                border
                                stripe
                                style="width: 100%"
                                v-loading="approvalLoading"
                            >
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="approvalStatus" label="审核状态" width="120">
                                    <template #default="{ row }">
                                        <el-tag
                                            :type="row.approvalStatus === '通过' ? 'success' : 'warning'"
                                            size="small"
                                        >
                                            {{ row.approvalStatus || '-' }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column label="审核时间" width="160">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.approvalTime) || '-' }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="approver" label="审核人" width="100" show-overflow-tooltip />
                                <el-table-column prop="remark" label="审核意见" min-width="200" show-overflow-tooltip />
                            </el-table>
                            <div v-if="!approvalRecords.length && !approvalLoading" class="empty-text">暂无审核记录</div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Box } from '@element-plus/icons-vue'
import moment from 'moment'
import myaxios from '@/http/MyAxios'

interface SalesDetailItem {
    productId: string | number
    productName: string
    productCode: string
    specificationModel?: string
    unitName?: string
    productTypeName?: string
    quantity: number
    unitPrice: number
    amount: number
    remark?: string
}

const route = useRoute()
const router = useRouter()

const info = reactive<any>({
    salesOrderId: route.query.salesOrderId,
    salesOrderNo: '',
    salesOrderDate: '',
    customerId: '',
    salesContact: '',
    salesContactPhone: '',
    customerName: '',
    organizationName: '',
    userName: '',
    salesOrderUser: '',
    salesOrderTime: '',
    remark: '',
    salesOrderStatus: '',
})

const detailList = ref<SalesDetailItem[]>([])
const activeTab = ref('details')
const summary = reactive({
    totalQuantity: 0,
    totalAmount: 0,
})
const fileList = ref<Array<{ name: string; url: string }>>([])
const outboundRecords = ref<any[]>([])
const returnRecords = ref<any[]>([])
const operationRecords = ref<any[]>([])
const approvalRecords = ref<any[]>([])
const outboundLoading = ref(false)
const returnLoading = ref(false)
const operationLoading = ref(false)
const approvalLoading = ref(false)
const rawDetailData = ref<any>(null)
const outboundLoaded = ref(false)
const returnLoaded = ref(false)
const operationLoaded = ref(false)
const getStatusTagType = (status: any) => {
    switch (Number(status)) {
        case 3:
            return 'success'
        case 1:
            return 'warning'
        case 4:
        case 5:
            return 'danger'
        default:
            return 'info'
    }
}


const formatDate = (date?: string | null) => {
    if (!date) return ''
    return moment(date).format('YYYY-MM-DD')
}

const formatDateTime = (date?: string | null) => {
    if (!date) return ''
    return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

const getStatusText = (status: any) => {
    switch (Number(status)) {
        case 0:
            return '草稿'
        case 1:
            return '待审核'
        case 2:
            return '部分出库'
        case 3:
            return '已出库'
        case 4:
            return '已关闭'
        case 5:
            return '已作废'
        default:
            return '-'
    }
}

const pickFirst = (source: Record<string, any> | null | undefined, keys: string[], defaultValue: any = '') => {
    if (!source) return defaultValue
    for (const key of keys) {
        if (key in source && source[key] !== undefined && source[key] !== null && source[key] !== '') {
            return source[key]
        }
    }
    return defaultValue
}

const tryParseJson = (value: any) => {
    if (typeof value !== 'string') return value
    try {
        const parsed = JSON.parse(value)
        return parsed
    } catch (error) {
        return value
    }
}

const normalizeList = (payload: any): any[] => {
    if (!payload) return []
    if (Array.isArray(payload)) return payload
    const parsed = tryParseJson(payload)
    if (Array.isArray(parsed)) return parsed
    if (typeof parsed !== 'object' || parsed === null) return []
    const candidateKeys = ['data', 'records', 'list', 'items', 'rows', 'detailList', 'Details', 'Data']
    for (const key of candidateKeys) {
        if (Array.isArray(parsed?.[key])) {
            return parsed[key]
        }
    }
    if (Array.isArray(parsed?.pages?.data)) {
        return parsed.pages.data
    }
    return []
}

const extractRecordsFromSource = (source: any, keys: string[]): any[] => {
    if (!source) return []
    for (const key of keys) {
        if (source[key] !== undefined) {
            const list = normalizeList(source[key])
            if (list.length) return list
        }
    }
    return []
}

const getRecordsFromRaw = (keys: string[]): any[] => {
    const candidates = [
        rawDetailData.value,
        rawDetailData.value?.salesOrder,
        rawDetailData.value?.salesOrderDetail,
        rawDetailData.value?.baseInfo,
        rawDetailData.value?.data,
    ]
    for (const candidate of candidates) {
        const list = extractRecordsFromSource(candidate, keys)
        if (list.length) return list
    }
    return []
}

const matchesSalesOrder = (record: any) => {
    if (!record) return false
    const currentId = info.salesOrderId ? String(info.salesOrderId) : ''
    const currentNo = info.salesOrderNo ? String(info.salesOrderNo) : ''
    const idCandidates = [
        record.salesOrderId,
        record.salesOrderID,
        record.orderId,
        record.orderID,
        record.businessId,
        record.documentId,
        record.sourceId,
        record.relatedId,
    ]
    const noCandidates = [
        record.salesOrderNo,
        record.orderNo,
        record.documentCode,
        record.referenceNo,
        record.businessNo,
        record.outboundCode,
        record.deliveryCode,
        record.returnCode,
    ]
    if (currentId && idCandidates.some((val) => val !== undefined && val !== null && String(val) === currentId)) {
        return true
    }
    if (currentNo && noCandidates.some((val) => val && String(val) === currentNo)) {
        return true
    }
    const content = record.operationContent || record.remark || record.description || ''
    return Boolean(currentNo && typeof content === 'string' && content.includes(currentNo))
}

const mapOutboundRecord = (item: any) => {
    return {
        outboundId: pickFirst(item, ['outboundId', 'deliveryId', 'id', 'documentId', 'businessId']),
        warehouseName: pickFirst(item, ['warehouseName', 'warehouse', 'stockName']),
        productName:
            pickFirst(item, ['productName', 'goodsName', 'productNames', 'goodsListText']) || '-',
        quantity: Number(
            pickFirst(item, ['quantity', 'outboundNum', 'deliveryNum', 'outboundQuantity'], 0),
        ),
        outboundTime:
            pickFirst(item, ['outboundTime', 'outboundDate', 'documentCreation', 'createTime']) || '',
        operator: pickFirst(item, ['operator', 'handlerProple', 'documentCreator', 'createor', 'userName']),
        remark: pickFirst(item, ['remark', 'outboundDescription', 'description', 'note']),
    }
}

const mapReturnRecord = (item: any) => ({
    returnId: pickFirst(item, ['returnId', 'goodsReturnsId', 'id', 'documentId']),
    productName:
        pickFirst(item, ['productName', 'goodsName', 'productNames', 'goodsReturnsGoodsText']) || '-',
    quantity: Number(
        pickFirst(
            item,
            ['quantity', 'returnQuantity', 'goodsReturnsQuantity', 'salesReturnQuantity', 'amount'],
            0,
        ),
    ),
    returnTime:
        pickFirst(item, ['returnTime', 'goodsReturnsDate', 'createTime', 'documentCreation']) || '',
    reason: pickFirst(item, ['reason', 'returnReason', 'goodsReturnsReason', 'remark', 'description']),
    operator: pickFirst(item, ['operator', 'goodsReturnsUser', 'createor', 'userName']),
})

const resolveOperationType = (type?: string) => {
    if (!type) return '未知'
    const normalized = String(type).toLowerCase()
    if (['add', 'create', '新增', '新建'].some((key) => normalized.includes(key))) return '新增'
    if (['update', 'edit', 'modify', '修改', '编辑'].some((key) => normalized.includes(key))) return '修改'
    if (['delete', 'remove', '删除'].some((key) => normalized.includes(key))) return '删除'
    if (['audit', 'approve', '审核'].some((key) => normalized.includes(key))) return '审核'
    if (['close', 'finish', 'complete', '关闭'].some((key) => normalized.includes(key))) return '关闭'
    if (['print', '打印'].some((key) => normalized.includes(key))) return '打印'
    if (['export', '导出'].some((key) => normalized.includes(key))) return '导出'
    return type
}

const resolveOperationContent = (item: any) => {
    const content =
        item.operationContent ||
        item.operateContent ||
        item.remark ||
        item.description ||
        item.content ||
        ''
    if (content) return content
    if (item.operationType) {
        return `${resolveOperationType(item.operationType)}订单`
    }
    if (info.salesOrderNo) {
        return `操作销售单【${info.salesOrderNo}】`
    }
    return '操作记录'
}

const mapOperationRecord = (item: any) => ({
    operationType: resolveOperationType(
        item.operationType || item.operateType || item.actionType || item.type,
    ),
    operationTime:
        item.operationTime || item.operateTime || item.createTime || item.createrTime || '',
    operator: item.operator || item.operateUser || item.userName || item.createUser || '',
    remark: resolveOperationContent(item),
})

const prefillRelatedRecordsFromRaw = () => {
    const outboundRaw = getRecordsFromRaw([
        'outboundRecords',
        'outboundList',
        'deliveryRecords',
        'stockoutRecords',
    ])
    if (outboundRaw.length) {
        outboundRecords.value = outboundRaw.filter(matchesSalesOrder).map(mapOutboundRecord)
        outboundLoaded.value = true
    }

    const returnRaw = getRecordsFromRaw(['returnRecords', 'salesReturnRecords', 'returnList', 'returns'])
    if (returnRaw.length) {
        returnRecords.value = returnRaw.filter(matchesSalesOrder).map(mapReturnRecord)
        returnLoaded.value = true
    }

    const operationRaw = getRecordsFromRaw([
        'operationRecords',
        'operationLogs',
        'logs',
        'operationList',
        'operateList',
    ])
    if (operationRaw.length) {
        operationRecords.value = operationRaw.filter(matchesSalesOrder).map(mapOperationRecord)
        operationLoaded.value = true
    }
}

const buildCleanParams = (params: Record<string, any>) => {
    const result: Record<string, any> = {}
    Object.keys(params).forEach((key) => {
        const value = params[key]
        if (value !== undefined && value !== null && value !== '') {
            result[key] = value
        }
    })
    return result
}

const loadOutboundRecords = async () => {
    if (outboundLoaded.value || outboundLoading.value) return
    outboundLoading.value = true
    try {
        const cached = getRecordsFromRaw([
            'outboundRecords',
            'outboundList',
            'deliveryRecords',
            'stockoutRecords',
        ])
        if (cached.length) {
            outboundRecords.value = cached.filter(matchesSalesOrder).map(mapOutboundRecord)
            outboundLoaded.value = true
            return
        }
        const params = buildCleanParams({
            salesOrderId: info.salesOrderId,
            salesOrderNo: info.salesOrderNo,
            customerId: info.customerId,
            pageindex: 1,
            pagesize: 50,
        })
        const apiCandidates = ['/api/Outbound/GetOutbound', '/api/Outbound/GetOutboundRecords']
        let list: any[] = []
        for (const api of apiCandidates) {
            try {
                const res = await myaxios.get(api, { params })
                if (res.data?.code === 200 || res.data?.success) {
                    const dataSection = res.data?.data || res.data
                    list = normalizeList(dataSection)
                    if (!list.length && Array.isArray(dataSection)) {
                        list = dataSection
                    }
                    if (list.length) break
                }
            } catch (error) {
                console.warn(`获取出库记录接口 ${api} 失败:`, error)
            }
        }
        outboundRecords.value = list.filter(matchesSalesOrder).map(mapOutboundRecord)
        outboundLoaded.value = true
    } catch (error) {
        console.error('获取出库记录失败:', error)
        ElMessage.error('获取出库记录失败，请稍后重试')
    } finally {
        outboundLoading.value = false
    }
}

const loadReturnRecords = async () => {
    if (returnLoaded.value || returnLoading.value) return
    returnLoading.value = true
    try {
        const cached = getRecordsFromRaw(['returnRecords', 'salesReturnRecords', 'returnList', 'returns'])
        if (cached.length) {
            returnRecords.value = cached.filter(matchesSalesOrder).map(mapReturnRecord)
            returnLoaded.value = true
            return
        }
        const params = buildCleanParams({
            salesOrderId: info.salesOrderId,
            salesOrderNo: info.salesOrderNo,
            customerId: info.customerId,
            pageindex: 1,
            pagesize: 50,
        })
        const apiCandidates = [
            '/api/SalesReturn/GetSalesReturns',
            '/api/SalesReturn/GetSalesReturn',
            '/api/SalesReturns/GetSalesReturns',
            '/api/SalesOrder/GetReturnRecords',
            '/api/ReturnOrder/GetReturnRecords',
            '/api/GoodsReturns/GetGoodsReturns',
        ]
        let list: any[] = []
        for (const api of apiCandidates) {
            try {
                const res = await myaxios.get(api, { params })
                if (res.data?.code === 200 || res.data?.success) {
                    const dataSection = res.data?.data || res.data
                    list = normalizeList(dataSection)
                    if (!list.length && Array.isArray(dataSection)) {
                        list = dataSection
                    }
                    if (list.length) break
                }
            } catch (error) {
                console.warn(`获取退货记录接口 ${api} 失败:`, error)
            }
        }
        returnRecords.value = list.filter(matchesSalesOrder).map(mapReturnRecord)
        returnLoaded.value = true
    } catch (error) {
        console.error('获取退货记录失败:', error)
        ElMessage.error('获取退货记录失败，请稍后重试')
    } finally {
        returnLoading.value = false
    }
}

const loadOperationRecords = async () => {
    if (operationLoaded.value || operationLoading.value) return
    operationLoading.value = true
    try {
        const cached = getRecordsFromRaw([
            'operationRecords',
            'operationLogs',
            'logs',
            'operationList',
            'operateList',
        ])
        if (cached.length) {
            operationRecords.value = cached.filter(matchesSalesOrder).map(mapOperationRecord)
            operationLoaded.value = true
            return
        }
        const params = buildCleanParams({
            salesOrderId: info.salesOrderId,
            businessId: info.salesOrderId,
            documentId: info.salesOrderId,
            moduleCode: 'SalesOrder',
            moduleName: '销售订单',
            businessType: 'SalesOrder',
            documentType: 'SalesOrder',
            salesOrderNo: info.salesOrderNo,
            pageindex: 1,
            pagesize: 50,
        })
        const apiCandidates = [
            '/api/SalesOrder/GetOperationRecords',
            '/api/SalesOrder/GetSalesOrderOperationLog',
            '/api/OperationLog/GetOperationRecords',
            '/api/Log/GetOperationRecords',
            '/api/OperationLog/GetList',
        ]
        let list: any[] = []
        for (const api of apiCandidates) {
            try {
                const res = await myaxios.get(api, { params })
                if (res.data?.code === 200) {
                    list = normalizeList(res.data.data)
                    if (!list.length && Array.isArray(res.data?.data)) {
                        list = res.data.data
                    }
                    if (list.length) break
                }
            } catch (error) {
                console.warn(`获取操作记录接口 ${api} 失败:`, error)
            }
        }
        const filtered = list.filter((item) => {
            if (matchesSalesOrder(item)) return true
            const content = item.operationContent || item.description || ''
            return Boolean(info.salesOrderNo && content && content.includes(info.salesOrderNo))
        })
        operationRecords.value = filtered.map(mapOperationRecord)
        operationLoaded.value = true
    } catch (error) {
        console.error('获取操作记录失败:', error)
        ElMessage.error('获取操作记录失败，请稍后重试')
    } finally {
        operationLoading.value = false
    }
}

const transformDetail = (detail: any): SalesDetailItem => {
    const quantity = Number(
        detail.quantity ?? detail.salesQuantity ?? detail.salesCount ?? 0,
    )
    const unitPriceRaw =
        detail.salePrice ??
        detail.salesPrice ??
        detail.unitPrice ??
        detail.salesUnitPrice ??
        0
    let unitPrice = Number(unitPriceRaw)
    if (!Number.isFinite(unitPrice) || unitPrice < 0) unitPrice = 0

    let amount = Number(
        detail.amount ??
            detail.totalAmount ??
            detail.totalPrice ??
            detail.salesAmount ??
            quantity * unitPrice,
    )
    if (!Number.isFinite(amount)) {
        amount = Number((quantity * unitPrice).toFixed(2))
    }
    if (quantity > 0 && (unitPrice === 0 || Math.abs(amount - quantity * unitPrice) >= 0.01)) {
        unitPrice = Number((amount / quantity).toFixed(4))
    }

    amount = Number((quantity * unitPrice).toFixed(2))

    return {
        productId:
            detail.productId ??
            detail.productID ??
            detail.id ??
            detail.ProductId ??
            '',
        productName:
            detail.productName || detail.ProductName || detail.goodsName || '',
        productCode:
            detail.productCode || detail.ProductCode || detail.goodsCode || '',
        specificationModel:
            detail.specificationModel ||
            detail.productSpecification ||
            detail.productUnit ||
            detail.specification ||
            '',
        unitName:
            detail.unitName ||
            detail.unitDisplayName ||
            detail.unit ||
            detail.productUnit ||
            '',
        productTypeName: detail.productTypeName || detail.ProductTypeName || '',
        quantity: quantity || 0,
        unitPrice,
        amount,
        remark: detail.remark || detail.memo || '',
    }
}

const extractDetailList = (data: any): any[] => {
    const candidates = [
        data?.salesDetails,
        data?.SalesDetails,
        data?.salesOrderDetails,
        data?.SalesOrderDetails,
        data?.goodsDetails,
        data?.detailList,
        data?.details,
        data?.data,
        data?.items,
    ]
    for (const candidate of candidates) {
        if (Array.isArray(candidate) && candidate.length) return candidate
        if (candidate && Array.isArray(candidate?.data) && candidate.data.length)
            return candidate.data
    }
    return []
}

const requestSalesOrderDetail = async (url: string, id: string | number) => {
    return myaxios.get(url, { params: { salesOrderId: id } })
}

const loadSalesOrderDetail = async () => {
    const id =
        route.query.salesOrderId ??
        route.params.salesOrderId ??
        info.salesOrderId ??
        ''
    if (!id) {
        ElMessage.error('缺少销售订单ID')
        router.push('/GetSalesOrder')
        return
    }

    let res =
        (await requestSalesOrderDetail('/api/SalesOrder/GetSalesOrderDetail', id).catch(
            () => null,
        )) ||
        (await requestSalesOrderDetail('/api/SalesOrder/GetSalesOrderDetails', id).catch(
            () => null,
        )) ||
        (await requestSalesOrderDetail('/api/SalesOrder/DetailSalesOrder', id).catch(
            () => null,
        ))

    if (!res) {
        ElMessage.error('获取销售订单详情失败')
        return
    }

    const result = res.data || {}
    if (result.code !== 200) {
        ElMessage.error(result.message || '获取销售订单详情失败')
        return
    }

    const data = result.data || {}
    rawDetailData.value = data
    const baseInfo = data.salesOrder || data.baseInfo || data
    Object.assign(info, {
        salesOrderId: baseInfo.salesOrderId ?? info.salesOrderId,
        salesOrderNo: baseInfo.salesOrderNo || baseInfo.SalesOrderNo || '',
        salesOrderDate: baseInfo.salesOrderDate || baseInfo.SalesOrderDate || '',
        customerId: baseInfo.customerId || baseInfo.CustomerId || '',
        customerName: baseInfo.customerName || baseInfo.CustomerName || '',
        salesContact: baseInfo.salesContact || baseInfo.contact || '',
        salesContactPhone:
            baseInfo.salesContactPhone || baseInfo.contactPhone || '',
        organizationName:
            baseInfo.organizationName ||
            baseInfo.OrganizationName ||
            baseInfo.salesDepartment ||
            '',
        userName: baseInfo.userName || baseInfo.UserName || baseInfo.salesUser || '',
        salesOrderUser: baseInfo.salesOrderUser || baseInfo.SalesOrderUser || '',
        salesOrderTime: baseInfo.salesOrderTime || baseInfo.SalesOrderTime || '',
        remark: baseInfo.remark || baseInfo.salesRemark || '',
        salesOrderStatus: baseInfo.salesOrderStatus ?? baseInfo.Status ?? '',
    })

    let detailArray = extractDetailList(result.data)
    if ((!detailArray || !detailArray.length) && baseInfo) {
        detailArray = extractDetailList(baseInfo)
    }

    detailList.value = (detailArray || []).map((item: any) => transformDetail(item))
    summary.totalQuantity = detailList.value.reduce(
        (sum, item) => sum + Number(item.quantity || 0),
        0,
    )
    summary.totalAmount = detailList.value.reduce(
        (sum, item) => sum + Number(item.amount || 0),
        0,
    )
    prefillRelatedRecordsFromRaw()
}

const handleEdit = () => {
    router.push({
        path: '/updateSalesOrder',
        query: { salesOrderId: info.salesOrderId },
    })
}

const handleDelete = () => {
    ElMessageBox.confirm('确认删除该销售订单吗？', '提示', {
        type: 'warning',
    })
        .then(async () => {
            try {
                const res = await myaxios.delete('/api/SalesOrder/DeleteSalesOrder', {
                    params: { salesOrderId: info.salesOrderId },
                })
                const result = res.data || {}
                if (result.code === 200) {
                    ElMessage.success('删除成功')
                    router.push('/GetSalesOrder')
                } else {
                    ElMessage.error(result.message || '删除失败')
                }
            } catch (error) {
                ElMessage.error('删除失败，请稍后重试')
            }
        })
        .catch(() => {})
}

const handleAudit = () => {
    ElMessage.info('审核功能暂未实现')
}

const handleClose = () => {
    router.push('/GetSalesOrder')
}

const handleCopyOrder = () => {
    if (!info.salesOrderNo) {
        ElMessage.warning('暂无单号可复制')
        return
    }
    navigator.clipboard
        .writeText(info.salesOrderNo)
        .then(() => {
            ElMessage.success('单号已复制')
        })
        .catch(() => {
            ElMessage.error('复制失败，请重试')
        })
}

const handlePrint = () => {
    window.print()
}

const handleTabChange = (name: string) => {
    if (name === 'outbound') {
        loadOutboundRecords()
    } else if (name === 'return') {
        loadReturnRecords()
    } else if (name === 'logs') {
        loadOperationRecords()
    }
}

onMounted(() => {
    loadSalesOrderDetail()
})
</script>

<style scoped>
.detail-page {
    padding: 20px;
    background: #f5f7fa;
    min-height: 100vh;
}

.detail-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    margin-bottom: 16px;
}

.detail-card :deep(.el-card__body) {
    padding: 24px;
}

.info-card {
    margin-bottom: 16px;
}

.detail-header {
    margin-bottom: 16px;
}

.header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 16px;
    margin-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
}

.title-area {
    display: flex;
    align-items: center;
    gap: 10px;
}

.order-label {
    font-size: 16px;
    color: #606266;
}

.order-number {
    font-size: 20px;
    font-weight: 600;
    color: #303133;
}

.status-tag {
    margin-left: 8px;
}

.action-buttons {
    display: flex;
    gap: 8px;
}

.info-content {
    margin-top: 0;
}

.info-row {
    margin-top: 16px;
}

.tabs-card :deep(.el-card__body) {
    padding: 0 24px 24px;
}

.tabs-section {
    margin-top: 0;
}

.detail-tabs {
    margin-top: 0;
}

.tab-content {
    padding: 20px 0;
}

.other-info-descriptions {
    margin-bottom: 32px;
}

.section-block {
    margin-bottom: 32px;
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #ebeef5;
}

.attachment-list {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
}

.file-link {
    padding: 8px 16px;
    border: 1px solid #b3d8ff;
    border-radius: 4px;
    background: #ecf5ff;
}

.empty-attachment {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #909399;
    padding: 40px 0;
    gap: 8px;
}

.attachment-icon {
    font-size: 40px;
}

.detail-summary {
    margin-top: 16px;
    padding: 16px 20px;
    background: #f5f7fa;
    border-radius: 4px;
    display: flex;
    gap: 32px;
    flex-wrap: wrap;
}

.amount-text {
    color: #f56c6c;
    font-weight: 600;
}

@media (max-width: 768px) {
    .header-section {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }

    .action-buttons {
        flex-wrap: wrap;
        width: 100%;
    }

    .detail-card :deep(.el-card__body) {
        padding: 16px;
    }
}
</style>
